import { defineStore } from 'pinia';
import { dict_dictDatas } from '@/api/dict';
import { EnabledStateEnum } from '@/common/enum/modules/common';
import { DictDefaultEnum } from '@/common/enum/modules/system';
import { ref } from 'vue';
export default defineStore('dict', () => {
  const cache = {};
  const dicts = ref({});

  const getDictBranch = (dictList, dictBranchVal) => {
    const result = [];
    dictList.forEach((item) => {
      let { children, dictBranch } = item;
      dictBranch = dictBranch ? dictBranch.split(',') : [];
      if (dictBranch.includes(dictBranchVal)) {
        if (children?.length) {
          item.children = getDictBranch(children, dictBranchVal);
          result.push(item);
        } else {
          result.push(item);
        }
      }
    });
    return result;
  };

  const getDictByCode = async (dictCode, dictBranch) => {
    const values = dicts.value[dictCode];
    if (values) {
      return new Promise((resolve) => {
        resolve(dictBranch ? getDictBranch(values, dictBranch) : values);
      });
    }
    if (!cache[dictCode]?.length) {
      cache[dictCode] = [];
      dict_dictDatas({ dictCode }).then(({ content }) => {
        const values = content
          ?.filter((item) => item.dataStatus === EnabledStateEnum.Enable)
          .map(({ dictValue, dictText, dictDefault, children, dictBranch }) => {
            return { dictValue, dictText, dictDefault, children, dictBranch };
          });
        dicts.value[dictCode] = values;
        const resolves = cache[dictCode];
        while (resolves.length) {
          const { resolve, dictBranch } = resolves.shift();
          resolve(dictBranch ? getDictBranch(values, dictBranch) : values);
        }
        delete cache[dictCode];
      });
    }
    return new Promise((resolve) => {
      cache[dictCode].push({ resolve, dictBranch });
    });
  };

  const getDictItem = (dictList, valueList) => {
    const result = [];
    dictList.forEach((item) => {
      const { dictValue, dictText, children } = item;
      if (children?.length) {
        result.push(...getDictItem(children, valueList));
      } else if (valueList.includes(dictValue)) {
        result.push({ value: dictValue, text: dictText });
      }
    });
    return result;
  };

  const getDictSelectText = async (dictCode, value) => {
    const dictValues = await getDictByCode(dictCode);
    const valueList = value.split(',');
    return getDictItem(dictValues, valueList);
  };

  const getTextByValue = async (dictCode, value) => {
    return (await getDictSelectText(dictCode, value)).map((item) => item.text);
  };

  const getDictDefaultValue = async (dictCode) => {
    const dictValues = await getDictByCode(dictCode);
    const values = dictValues.filter((item) => item.default === DictDefaultEnum.defaultValue);
    return values.map((item) => item.value);
  };

  return {
    getDictByCode,
    getTextByValue,
    getDictDefaultValue,
    getDictSelectText
  };
});
